# -*-coding:utf-8-*-
from __future__ import unicode_literals

import copy
import datetime
import re
import sys
import time

from .logic_adapter import LogicAdapter
from ..zyrobot.mysqlconn import conn
from logging import getLogger

web_logger = getLogger('web_logger')


class newStatementclass(object):

    def __init__(self, text, **kwargs):

        try:
            text = str(text)
        except UnicodeEncodeError:
            pass

        self.text = text
        self.confidence = 0


class Bestqualitquestion(LogicAdapter):
    """
    A logic adater that returns a response based on known responses to
    the closest matches to the input statement.

    """

    def get(self, input_statement):
        """
        Takes a statement string and a list of statement strings.
        Returns the closest matching statement from the list.


        """
        #  print('input_statement',input_statement)
        statement_list = self.chatbot.storage.get_response_statements()

        closest_match = input_statement

        closest_match.confidence = self.confidence_threshold

        for statement in statement_list:
            confidence = self.compare_statements(statement, input_statement)
            # print('confidence',confidence)
            if confidence > closest_match.confidence:
                web_logger.info('cid:%s serviceid:%s confidence:%s statement:%s input_statement:%s',
                                self.cid, self.serviceid, confidence, statement, input_statement)

                statement.confidence = confidence
                closest_match = statement

        return closest_match

    def selhavebackanswerid(self, cid, serviceid):
        sql = "select r.answerid from zy_rcustomerquestion q,zy_robotanswer r  \
        where q.cid='" + str(cid) + "' and q.serviceid='" + str(
            serviceid) + "' and q.sessionid=r.sessionid and r.answerid is not NULL GROUP BY  answerid"
        answeridgroup = conn.mysql_sel(sql, self.dbname, self.cid)
        # print('sql',sql)
        return answeridgroup

    def can_process(self, statement):
        """
        Check that the chatbot's storage adapter is available to the logic
        adapter and there is at least one statement in the database.

        """
        # return self.chatbot.storage.count()
        return True

    def fuzzyquery(self, cmpid, serviceid, text, industryid):
        sql = "select  q.quesid,q.keywords from zt_know_question q where q.cmpid='" + str(
            cmpid) + "' and q.serviceid is null and q.keywords!='' and q.state=1 "
        keywords = conn.mysql_sel(sql, self.dbname, self.cid)

        return keywords

    def selanswerid(self, quesid):
        sql = "select a.answerid from zt_know_answer a where a.quesid='" + str(quesid) + "' ORDER BY a.sort  LIMIT 0,1"

        answerid = conn.mysql_selrowid(sql, self.dbname, self.cid)
        return answerid

    def tracommfuzzyquery(self, cmpid, serviceid, text, industryid):
        sql = "select  q.quesid,q.keywords from zt_know_question q where  q.keywords!='' and q.state=1 "

        if industryid != None and industryid != "":
            sql = sql + " and industryid= '" + str(industryid) + "'"
        keywords = conn.mysql_sel(sql, self.dbname, self.cid)

        return keywords

    def selfuzzyqueryanswer(self, keywork, cmpid, serviceid):
        sql = "select q.answerid from zt_know_question q where q.cmpid='" + str(cmpid) + "' and" \
                                                                                         " q.serviceid='" + str(
            serviceid) + "' and  FIND_IN_SET( '" + str(keywork) + "',q.keywords) ORDER BY q.createtime DESC LIMIT 0,1"
        keywords = conn.mysql_selrowid(sql, self.dbname, self.cid)

        return keywords

    def fromquestion(self, answerid):
        sql = "select a.quesid from zt_know_answer a where a.answerid='" + str(answerid) + "' "
        questionid = conn.mysql_selrowid(sql, self.dbname, self.cid)
        return questionid

    def insertquestion(self, answerid, cid, cmpid):
        sql = "select a.quesid from zt_know_answer a where a.answerid='" + str(answerid) + "' "
        questionid = conn.mysql_selrowid(sql, self.dbname, cid)
        if questionid == None or questionid == '':
            sql = "select q.quesid from zt_know_question q where q.answerid='" + str(answerid) + "'"
            questionid = conn.mysql_selrowid(sql, self.dbname, cid)

        insertcount = str(0)

        if questionid != conn.err:
            sqlinsert = "INSERT into zt_cmp_robot_respond(cmpid,cid,questionid,session_data,session_sort) VALUES ('" + str(
                cmpid) + "','" + str(cid) + "','" + str(
                questionid) + "','" + self.session_data + "','" + self.session_sort + "')"

            insertcount = conn.mysql_insert(sqlinsert, self.dbname, cid)

        return str(insertcount)

    def ifhoodlemobole(self, askid):
        sql = "select a.attitude from zt_know_hoodlemobile_answer a where a.HoodleMobileid='" + str(
            askid) + "' ORDER BY a.attitude "
        attitudelist = conn.mysql_sel(sql, self.dbname, self.cid)

        attitudelist = attitudelist + ((6,), (7,), (11,))
        return attitudelist

    # 查询技能
    def selskill(self, serviceid):
        sql = "SELECT s.skillid,s.keywords from zt_skill s  where s.state=1 and keywords!='' and keywords is not null and s.serviceid='" + str(
            serviceid) + "'"
        keywords = conn.mysql_sel(sql, self.dbname, self.cid)

        return keywords

    def backanswer(self, statement_list, closest_match, input_statement):
        if statement_list != None and len(statement_list) != 0:
            closest_match.confidence = 0.85

            maxsocre = 0
            maxtext = ''
            for statement in statement_list:
                # print(statement)
                socre = 1
                if statement.text.count('$') >= 1:
                    socre = statement.text.split('$')[-1]
                    newstatement = statement.text[:statement.text.rfind('$')]

                    # print('33',newstatement,socre)
                    if newstatement.strip() != "" and newstatement.strip() in str(input_statement):
                        if float(socre) == float(maxsocre):
                            if len(statement.text) > len(maxtext):
                                maxtext = statement.text
                                maxsocre = socre
                                web_logger.debug('socre=maxsocre cid:%s maxtext:%s maxsocre:%s', self.cid,
                                                 statement.text, maxsocre)

                        elif float(socre) > float(maxsocre):
                            maxtext = statement.text
                            maxsocre = socre
                            web_logger.debug('socre>maxsocre cid:%s maxtext:%s socre:%s maxsocre:%s ', self.cid,
                                             maxtext, socre, maxsocre)

                ottherstatement = copy.deepcopy(statement)

                if statement.text.count('$') >= 1:
                    ottherstatement.text = str(statement.text).split('$')[0]
                if ottherstatement != "":
                    confidence = self.compare_statements(ottherstatement, input_statement)
                    # print('2',confidence,'confidence',statement,ottherstatement)
                else:
                    confidence = 0
                if confidence > closest_match.confidence:
                    web_logger.debug('serviceid:%s confidence:%s statement:%s input_statement:%s',
                                     self.serviceid, confidence, statement, input_statement)
                    statement.confidence = confidence
                    closest_match = statement

            if maxsocre != 0 and closest_match.confidence != 1:
                # closest_match.confidence = maxsocre
                # closest_match.text = maxtext

                response_list = self.chatbot.storage.filter(
                    in_response_to__contains=maxtext
                )
                if len(response_list) != 0:
                    response = self.select_response(input_statement, response_list)
                    response.confidence = maxsocre

                    if response.text != self.default_response:
                        response.text = 'attitude' + response.text

                    return response

            response_list = self.chatbot.storage.filter(
                in_response_to__contains=closest_match.text
            )
            if len(response_list) != 0:
                response = self.select_response(input_statement, response_list)
                response.confidence = closest_match.confidence

                if response.text != self.default_response:
                    response.text = 'attitude' + response.text

                return response

    def selmongodbdata(self, data, tablename):
        statement_data = self.chatbot.storage.get_response_statements_database(data, tablename)
        if len(statement_data) != 0:
            statement_list = statement_data
            return statement_list

    # 查询公共行业问题
    def selindustrycomm(self, industryid, closest_match, input_statement):
        ifhavetable = self.chatbot.storage.seltable('industry' + str(industryid), '')

        if str(ifhavetable) != '0':
            statement_data = self.selmongodbdata('industry' + str(industryid), '')
            web_logger.debug('serviceid:%s industryid:%s', self.serviceid, industryid)
            backanswerdata = self.backanswer(statement_data, closest_match, input_statement)
            if backanswerdata != None:
                alltext = backanswerdata.text[8:]
                allconfidence = backanswerdata.confidence
                return (allconfidence, alltext)

    def groo_keywork(self, input_statement, response):
        keywords = self.fuzzyquery(self.cmpid, self.serviceid, input_statement, '')
        if len(keywords) != 0:
            quesid = ''
            maxkeywordtext = ''
            for i in keywords:
                worklist = []
                try:
                    newzheng = i[1].replace(",", "|")
                    pipe_word = re.compile(newzheng)
                    worklist = re.findall(pipe_word, input_statement.text)
                except:
                    web_logger.debug('serviceid:%s newzheng-i[1]:%s', self.serviceid, i[1])

                if len(worklist) != 0:
                    worklen = 0
                    workend = ''
                    for work in worklist:
                        if len(work) > worklen:
                            worklen = len(work)
                            workend = work
                    if maxkeywordtext != "":
                        if worklen > len(maxkeywordtext):
                            quesid = i[0]
                            maxkeywordtext = workend
                    else:
                        quesid = i[0]
                        maxkeywordtext = workend

            if maxkeywordtext != "":
                web_logger.debug('serviceid:%s quesid:%s maxkeywordtext:%s', self.serviceid, quesid, maxkeywordtext)
                response.text = 'A' + str(quesid)
                response.confidence = 1
                return response

    # 态度正则查询
    def sel_reg_data(self):
        sql = "SELECT a.regwords,a.attitude from zt_know_hoodlemobile_answer a where a.HoodleMobileid='" + str(
            self.askid) + "' and a.regwords!='' and a.regwords is not NULL"
        regword = conn.mysql_sel(sql, self.dbname, self.cid)
        return regword

    def process(self, input_statement):
        closest_match = self.get(input_statement)

        self.logger.info('Using "{}" as a close match to "{}"'.format(
            input_statement.text, closest_match.text
        ))
        response_list = self.chatbot.storage.filter(
            in_response_to__contains=closest_match.text
        )
        if response_list:
            self.logger.info(
                'Selecting response from {} optimal responses.'.format(
                    len(response_list)
                )
            )

            response = self.select_response(input_statement, response_list)
            response.confidence = closest_match.confidence
            response.text = 'A' + str(self.fromquestion(response.text[1:]))
            self.logger.info('Response selected. Using "{}"'.format(response.text))

            if self.cmpid != '-1' and self.cid != '-1' and response.confidence != 1:
                data = self.groo_keywork(input_statement, response)
                if data != None:
                    return data
            response.confidence = 1
        else:
            response = closest_match
            if self.cmpid != '-1' and self.cid != '-1':
                data = self.groo_keywork(input_statement, response)
                if data != None:
                    return data

            else:
                response.confidence = 0
                response.text = self.default_response

            self.logger.info(
                'No response to "{}" found. Selecting a random response.'.format(
                    closest_match.text
                )
            )
        return response
